package com.kingviker.example.handler3;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class MyCustomDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if(in.readableBytes()>8){
            if (in.readInt() == MyCustomProtocol.HEAD_FLAG) {
                int length = in.readInt();
                if (in.readableBytes() < length) {
                    in.resetReaderIndex();
                } else if(in.readableBytes()>2048) {
                    in.skipBytes(in.readableBytes());
                }else{
                    MyCustomProtocol customProtocol = new MyCustomProtocol();
                    customProtocol.setLength(length);
                    byte[] data = new byte[length];
                    in.readBytes(data);
                    customProtocol.setContent(data);
                    out.add(customProtocol);
                }
            }
        }
    }
}
